import { ITypeState } from '@/models/typeModel';
import { IIssue } from '@/types/issue';
import { formatDate } from '@/utils/tools';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'umi';

// 请求方法
import IssueController from '@/services/issue';
import UserController from '@/services/user';

const IssueDetail: React.FC = () => {
  const { issueId } = useParams(); // 获取可能传递过来的 id
  const dispatch = useDispatch(); // 获取 dispatch
  const [issueInfo, setIssueInfo] = useState<IIssue>();
  const [typeName, setTypeName] = useState<string>();
  const [userName, setUserName] = useState(null);

  // 从仓库获取类型列表
  const { typeList }: ITypeState = useSelector((state: any) => state.type);

  useEffect(() => {
    // 如果类型列表为空，则初始化一次
    if (!typeList.length) {
      dispatch({
        type: 'type/_initTypeList',
      });
    }

    async function fetchData() {
      // 根据问答 id 获取该问答具体的信息
      if (!issueId) return;
      const { data } = await IssueController.getIssueById(issueId);
      setIssueInfo(data);
      // 获取 typeId 对应的 typeName
      const type = typeList.find((item) => item._id === data.typeId);
      setTypeName(type?.typeName);
      // 获取 userId 对应的 nickName
      const result = await UserController.getUserById(data.userId);
      setUserName(result.data.nickname);
    }
    fetchData();
  }, []);

  return (
    <PageContainer>
      <div
        className="container"
        style={{
          width: '100%',
          margin: 'auto',
        }}
      >
        <Card
          title={issueInfo?.issueTitle}
          variant="borderless"
          style={{
            marginTop: 20,
          }}
          extra={
            <Tag color="purple" key={issueInfo?.typeId}>
              {typeName}
            </Tag>
          }
        >
          <h2>提问用户</h2>
          <p>
            <Tag color="volcano" key={issueInfo?.userId}>
              {userName}
            </Tag>
          </p>
          <h2>问题描述</h2>
          <p>
            <div
              dangerouslySetInnerHTML={{
                __html: issueInfo?.issueContent ? issueInfo?.issueContent : '',
              }}
            ></div>
          </p>
          <h2>提问时间</h2>
          <p>{formatDate(issueInfo?.issueDate)}</p>
          <h3>浏览数：{issueInfo?.scanNumber}</h3>
          <p></p>
          <h3>评论数：{issueInfo?.scanNumber}</h3>
        </Card>
      </div>
    </PageContainer>
  );
};

export default IssueDetail;
